<?php

namespace App\Service\Impl;

use App\Dto\AddContentDTO;
use App\Exceptions\InsertException;
use App\Exceptions\NullRuleException;
use App\Exceptions\URLDuplicateException;
use App\Models\Content;
use App\Service\ContentService;
use Illuminate\Support\Facades\Http;
use Symfony\Component\DomCrawler\Crawler;

class ContentServiceImpl implements ContentService
{

    function insert(AddContentDTO $contentDTO)
    {
        // 检查数据是否存在
        $url = $contentDTO->getUrl();
        $content = new Content();
        $row = $content->where("url", $url)->first();
        if ($row != null) {
            throw new URLDuplicateException();
        }

        $content->url = $contentDTO->getUrl();
        $content->leixing = $contentDTO->getLeixing();
        // 请求URL获取正文内容
        $response = Http::get($url);
        $html = $response->body();

        // 使用第三方Symfony\Crawler解析html正文
        $crawler = new Crawler($html);
        $content->title = $crawler->filterXPath("//title")->text();
        $content->key = $crawler->filterXPath("//meta[@name=\"keywords\"]")->attr("content");
        $content->description = $crawler->filterXPath("//meta[@name=\"description\"]")->attr("content");
        // 采集正文
        $rule = $contentDTO->getRule();
        if (!array_key_exists("main_content_rule", $rule) || trim($rule["main_content_rule"]) === "") {
            throw new NullRuleException();
        }
        $content->content = $crawler->filter($rule["main_content_rule"])->html();
        // 保存到数据库
        $result = $content->save();
        if (!$result) {
            throw new InsertException();
        }
    }
}
